package cn.cold.album.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import cn.cold.album.model.AlbumUserDetail;
import cn.cold.album.model.UserInfo;
import cn.cold.album.model.UserType;
import cn.cold.album.repository.UserInfoRepository;
import cn.cold.album.repository.UserTypeRepository;

@Service
public class AlbumUserDetailService implements UserDetailsService {
	private static final Logger log = LoggerFactory.getLogger(AlbumUserDetailService.class);
	@Autowired
	private UserInfoRepository userRepository;
	@Autowired
	private UserTypeRepository userTypeRepository;
	
	@EventListener(ContextRefreshedEvent.class)
	public void start() {
		UserType usertype = new UserType(1,"ROLE_ALL");
		userTypeRepository.save(usertype);
		UserInfo info = new UserInfo(1,"admin","admin",true,usertype);
		userRepository.save(info);
		try {
			log.info("chushihua,'{}'.",new ObjectMapper().writeValueAsString(info));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
	}
	

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		if (username == null || username =="") {
			log.warn("请求登录操作,但是Username为NULL");
			throw new UsernameNotFoundException("请求登录操作,但是Username为NULL");
		}
		UserInfo info = userRepository.findByusername(username);
		if (info == null) {
			throw new UsernameNotFoundException("对不起用户不存在");
		}
		UserDetails details = new AlbumUserDetail(info);
		return details;
	}

}
